import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_model/media_content.dart';
import 'package:xvideos/hj_page/cartoon_business/widget/acg_source_manager.dart';
import 'package:xvideos/hj_utils/api_service/acg_service.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/tools_base/loading/LoadingHelper.dart';
import 'package:xvideos/tools_base/widget/scroll_positioned_list/src/item_positions_listener.dart';
import 'package:xvideos/tools_base/widget/scroll_positioned_list/src/scrollable_positioned_list.dart';

class CartoonReadLogic extends GetxController {
  MediaContent? detailInfo;
  int currentEpisode = 0; //当前的子集数 ，从1开始自增
  final ACGSourceManager manager;
  bool showMenu = false;

  int readIndex = 1; // 当前在第几页张图
  RxBool showProgress = false.obs; //展示进度
  double bottomHeight = 155;
  int animationTime = 250; //显示时间
  bool? autoPlayEnable = true; //是否自动滑屏
  Timer? timer;
  bool autoPlay = false; //是否自动播放
  int edgeState = 0; //距离状态 0-顶部，1-底部 2-中间任何位置
  RxBool sortType = true.obs; //排序类型 true-正序 false-倒序

  double readScale = 0; //播放比例

  int get imgsLength => detailInfo?.urlSet?.length ?? 1;

  final ItemScrollController itemSctr = ItemScrollController();
  final ScrollOffsetController scrollOffsetCtl = ScrollOffsetController();
  final ItemPositionsListener itemListener = ItemPositionsListener.create();

  CartoonReadLogic(this.manager) : currentEpisode = manager.index;

  @override
  void onInit() {
    super.onInit();

    itemListener.itemPositions.addListener(() {
      int count = detailInfo?.urlSet?.length ?? 0;
      if (itemListener.itemPositions.value.lastOrNull != null) {
        readIndex = itemListener.itemPositions.value.last.index;
      } else {
        readIndex = 0;
      }
      if (itemListener.itemPositions.value.first.index == 0) {
        edgeState = 0;
      } else if (itemListener.itemPositions.value.last.index == count - 1) {
        edgeState = 1;
        onChangeAutoPlay(false);
      } else {
        edgeState = 2;
      }
      readScale = readIndex / imgsLength;
      // print('itemPositionsListener = $readIndex, readScale = $readScale');
      update(['slider']); //刷新
    });
  }

  @override
  onReady() async {
    super.onReady();
    loadData();
  }

  @override
  void onClose() {
    stopTimer();
    itemListener.itemPositions.removeListener(() {});
    super.onClose();
  }

  //获取有声小说
  loadData({bool showLoading = false}) async {
    if (showLoading) LoadingHelper.showLoading();
    final model = await manager.getComicsMediaContent(index: currentEpisode);
    if (showLoading) LoadingHelper.dismissLoading();
    setData(model);
    update();
  }

  //true- 下一集 false- 上一集
  loadOtherEpisode(bool next) async {
    int index = next ? currentEpisode + 1 : currentEpisode - 1;
    if (index < 0) {
      showToast('这是第一${manager.mediaInfo?.unit}了喔～');
      return;
    }
    if (index > manager.allEpisodes.length - 1) {
      showToast('这是最后一${manager.mediaInfo?.unit}了喔～');
      return;
    }
    final model = await manager.getComicsMediaContent(index: index);
    currentEpisode = index;
    setData(model);
    update();
  }

  loadDataWithIndex(int index) async {
    LoadingHelper.showLoading();
    MediaContent? model = await ACGService.getMediaDetailInfo(
      episodeNumber: index,
      mediaId: manager.mediaInfo?.id,
    );
    LoadingHelper.dismissLoading();
    if (model != null) {
      currentEpisode = index - 1;
      setData(model);
    }

    update();
  }

  setData(MediaContent? model) {
    if (model != null) {
      detailInfo = model; //子集详情
      readIndex = 0; //阅读图片index
      // HistoryRecordUtil.saveNovalRecord(manager.mediaInfo?.id, model.episodeNumber ?? 0);
    } else {
      detailInfo = MediaContent();
    }
  }

  //跳转到具体的图片
  updateReadPicIndex(double value) {
    readScale = value;
    update(['slider']);
    readIndex = (imgsLength * readScale).toInt();
    print('readIndex === all = $imgsLength, $readScale $readIndex');
    itemSctr.jumpTo(index: readIndex);
  }

  changeShowMenu() {
    showMenu = !showMenu;
    update(['header', 'footer', 'like']);
  }

  //是否自动播放
  onChangeAutoPlay(bool play) async {
    if (autoPlayEnable == false) return;
    showMenu = !play;
    if (play) {
      update(['header', 'footer', 'autoplay', 'like']);
      Future.delayed(Duration(milliseconds: 300)).then((value) {
        autoPlay = play;
        update(['autoplay']);
      });
      startTimer();
    } else {
      stopTimer();
      autoPlay = play;
      update(['header', 'footer', 'autoplay', 'like']);
    }
  }

  //启动自动播放定时器
  startTimer() {
    timer = Timer.periodic(const Duration(milliseconds: 500), (timer) {
      scrollOffsetCtl.animateScroll(offset: 50, duration: Duration(milliseconds: 500));
    });
  }

  stopTimer() {
    if (timer != null) {
      timer?.cancel();
      timer = null;
    }
  }

  onScrollAction(ScrollController scrollController) {
    if (showMenu == true) {
      showMenu = false; //不显示菜单
      update();
    }
  }
}
